<template>
  <div>
    <div style="display: flex; align-items: center; margin-bottom: 15px;">
      <el-button type="primary" @click="openAddDialog" style="margin-right: 10px;">添加用户</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column
          label="序号"
          width="100">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="login" label="登录账号" width="180"></el-table-column>
      <el-table-column prop="name" label="真实姓名" width="180"></el-table-column>
      <el-table-column prop="type" label="用户类型" width="180">
        <template #default="{ row }">
          {{ getUserType(row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ getUserStatus(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="lastLogin" label="最后登录时间" width="180">
        <template v-slot="scope">
          <span v-if="scope.row.lastLogin">{{ scope.row.lastLogin }}</span>
          <span v-else>从未登录</span>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button @click="openEditDialog(row)" type="text" size="small">修改</el-button>
          <el-button @click="deleteUser(row)" type="text" size="small" style="color: red;">删除</el-button>
          <el-button @click="resetPassword(row)" type="text" size="small">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        align="center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 15px;"
    ></el-pagination>

    <el-dialog title="添加用户" :visible.sync="addDialogVisible">
      <el-form :model="newUser" ref="addUserForm">
        <el-form-item label="登录账号" prop="login">
          <el-input v-model="newUser.login" required></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="newUser.name" required></el-input>
        </el-form-item>
        <el-form-item label="用户类型" prop="type">
          <el-select v-model="newUser.type" placeholder="请选择用户类型">
            <el-option v-for="item in userTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="newUser.status" placeholder="请选择状态">
            <el-option label="正常" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="editDialogVisible">
      <el-form :model="currentUser" ref="editUserForm">
        <el-form-item label="登录账号" prop="login">
          <el-input v-model="currentUser.login" disabled></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="currentUser.name" required></el-input>
        </el-form-item>
        <el-form-item label="用户类型" prop="type">
          <el-select v-model="currentUser.type" placeholder="请选择用户类型">
            <el-option v-for="item in userTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="currentUser.status" placeholder="请选择状态">
            <el-option label="正常" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getUserPage, addUser, deleteUser, updateUser, resetPassword} from '@/api/system/user'; // 导入 getUserPage 函数

export default {
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      newUser: {
        login: '',
        name: '',
        type: 1,
        status: 1,
      },
      currentUser: {},
      userTypes: [
        { value: 1, label: '用户管理员' },
        { value: 2, label: '题库管理员' },
        { value: 3, label: '题库使用者' },
        { value: 4, label: '普通用户' }
      ],
    };
  },
  created() {
    this.fetchUsers();
  },
  methods: {
    fetchUsers() {
      getUserPage(this.currentPage, this.pageSize)
          .then(response => {
            this.tableData = response.data.records; // 假设后端返回的数据结构中包含 records 数组
            this.total = response.data.total; // 假设后端返回的数据中还包含总记录数
          })
          .catch(error => {
            console.error("获取用户数据失败:", error);
          });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 重置到第一页
      this.fetchUsers();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchUsers();
    },
    openAddDialog() {
      this.newUser = {}; // 重置新用户信息
      this.addDialogVisible = true;
    },
    addUser() {
      // 使用 Promise 处理方式添加用户
      addUser(this.newUser)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('用户添加成功！');
              this.addDialogVisible = false; // 关闭对话框
              this.fetchUsers(); // 刷新用户列表
          }
          })
          .catch(error => {
            console.error('添加用户失败:', error);
            this.$message.error('添加用户失败！');
          });
    },
    openEditDialog(user) {
      this.currentUser = { ...user }; // 复制用户信息
      this.editDialogVisible = true;
    },
    updateUser() {
      updateUser(this.currentUser)
          .then(response => {
            this.$message.success('用户修改成功！');
            this.editDialogVisible = false; // 关闭对话框
            this.fetchUsers(); // 刷新用户列表
          })
          .catch(error => {
            console.error('修改用户失败:', error);
            this.$message.error('修改用户失败！');
          });
    },
    deleteUser(user) {
      console.log(user)
      this.$confirm('确定删除该用户吗?', '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(user) // 使用用户 ID 调用删除接口
            .then(response => {
              this.$message.success('用户删除成功！');
              this.fetchUsers(); // 刷新用户列表
            })
            .catch(error => {
              console.error('删除用户失败:', error);
              this.$message.error('删除用户失败！');
            });
      });
    },
    resetPassword(user) {
      this.$confirm('确定重置该用户的密码吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPassword(user.id) // 使用用户 ID 调用重置密码接口
            .then(response => {
              this.$message.success('密码重置成功！');
              this.fetchUsers(); // 刷新用户列表
            })
            .catch(error => {
              console.error('重置密码失败:', error);
              this.$message.error('重置密码失败！');
            });
      });
    },
    getUserType(type) {
      const types = {
        1: '用户管理员',
        2: '题库管理员',
        3: '题库使用者',
        4: '普通用户'
      };
      return types[type] || '未知类型';
    },
    getUserStatus(status) {
      return status === 1 ? '正常' : '禁用';
    },
    renderIndex(row, index) {
      return (this.currentPage - 1) * this.pageSize + index + 1; // 计算序号
    }
  }
};
</script>

<style scoped>
.table-container {
  padding: 20px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
